<script lang="ts" setup>
import { ref, reactive, type PropType } from 'vue'
import {
  cardProps,
  type FormInst,
  NForm,
  NFormItem,
  NInput,
  type FormRules,
  useMessage,
  type FormItemRule
} from 'naive-ui'
import VDialogContent from '@/views/OA/Common/DialogContent.vue'
import type { UserModel } from '@/api/user'
import { sendRequest } from '@/utils/api'
import { usePermissionStore } from '@/stores/permission'

const props = defineProps({
  ...cardProps,
  username: [String, undefined] as PropType<string | undefined>
})
const emit = defineEmits<{
  (event: 'close'): void
}>()

const message = useMessage()
const formRef = ref<FormInst | null>(null)
const form = reactive({} as UserModel & { newPassword: string; confirmPassword: string })
const loading = ref(false)
const permissionStore = usePermissionStore()

const passwordValidator = (_: FormItemRule, value: string) => {
  if (!value) return new Error('密码为必填项，请输入密码')
  if (!/^(?=.*[A-Z])(?=.*[a-z])(?=.*\d).+$/.test(value)) {
    return new Error('密码必须包含大小写字母和数字')
  }
  if (value.length < 8) return new Error('密码长度不能小于8位')
  return true
}
const formRules: FormRules = {
  password: {
    required: true,
    trigger: ['input', 'blur'],
    message: '原密码不能为空'
  },
  newPassword: {
    required: true,
    trigger: ['input', 'blur'],
    validator: passwordValidator
  },
  confirmPassword: [
    {
      required: true,
      trigger: ['input', 'blur'],
      validator: (_, value) => {
        if (!value) return new Error('确认密码不能为空')
        return value === form.newPassword || new Error('两次密码不一致')
      }
    },
    {
      required: true,
      trigger: ['input', 'blur'],
      validator: passwordValidator
    }
  ]
}

const submit = () => {
  formRef.value?.validate(async (err) => {
    if (err) return
    loading.value = true
    const [error, res] = await sendRequest({
      module: 'user',
      api: props.username ? 'pwd' : 'password',
      override: {
        data: {
          password: form.password,
          newPassword: form.newPassword,
          userName: props.username || permissionStore.userInfo?.loginName
        }
      }
    })
    loading.value = false

    if (error) return message.error(error.message)
    if (res.code !== 0) return message.error(res.msg)
    message.success(res.msg)
    emit('close')
  })
}
</script>

<template>
  <VDialogContent
    action
    @close="$emit('close')"
    @submit="submit"
    title="修改密码"
  >
    <NForm
      :model="form"
      :rules="formRules"
      ref="formRef"
      label-placement="left"
      label-width="80"
      size="small"
      style="min-width: 450px"
    >
      <NFormItem
        label="原密码"
        path="password"
      >
        <NInput
          v-model:value="form.password"
          show-password-on="click"
          type="password"
        />
      </NFormItem>
      <NFormItem
        label="密码"
        path="newPassword"
      >
        <NInput
          v-model:value="form.newPassword"
          show-password-on="click"
          type="password"
        />
      </NFormItem>
      <NFormItem
        label="确认密码"
        path="confirmPassword"
      >
        <NInput
          v-model:value="form.confirmPassword"
          show-password-on="click"
          type="password"
        />
      </NFormItem>
    </NForm>
  </VDialogContent>
</template>
